package com.wetool.service.commodity;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.wetool.entity.PublicCategory;
import com.wetool.exception.CategoryNotFindException;
import com.wetool.exception.ChangeIsLeafException;
import com.wetool.exception.DataRelationException;
import com.wetool.exception.NodeRelationException;
import com.wetool.jpa.PublicCategoryRepo;
import com.wetool.jpa.PublicCommodityRepo;
import com.wetool.model.PublicCategoryAdd;
import com.wetool.model.PublicCategoryModify;
import com.wetool.model.CategoryTree;

@Component
public class PublicCategoryService {
	final static int OPT_TYPE_UPDATE = 0;
	final static int OPT_TYPE_DEL = 1;

	@Autowired
	private PublicCategoryRepo publicCategoryRepo;

	@Autowired
	private PublicCommodityRepo publicCommodityRepo;

	/**
	 * 查询所有公共分类
	 * @return List<PublicCategory> 分类集合
	 */
	public List<PublicCategory> findAll() {
		return publicCategoryRepo.findAll();
	}
	
	/**
	 * 商品分类查询
	 * 
	 * @return 商品分类树结构
	 */
	public List<CategoryTree> getTree(Long publicCategoryId) {
		PublicCategory root = findOne(publicCategoryId);
		List<CategoryTree> result = new ArrayList<CategoryTree>();
		Long parentId = null;
		if (root.getParent() != null) {
			parentId =root.getParent().getId();
		}
		CategoryTree tree = build(root.getChildren(),
				new CategoryTree(root.getId(), root.getCategoryName(), parentId, root.isLeaf()));
		result.add(new CategoryTree(tree.getValue(), tree.getLabel(),tree.getParent(), tree.isLeaf()));
		if (tree.getChildren() != null) {
			result.addAll(tree.getChildren());
		}
		return result;
	}

	private CategoryTree build(List<PublicCategory> categorys, CategoryTree tree) {
		if (categorys != null && categorys.size() > 0) {
			for (PublicCategory children : categorys) {
				CategoryTree node = new CategoryTree(children.getId(), children.getCategoryName(), children.getParent().getId(), children.isLeaf());
				if (tree.getChildren() == null) {
					List<CategoryTree> nodes = new ArrayList<CategoryTree>();
					nodes.add(node);
					tree.setChildren(nodes);
				} else {
					tree.getChildren().add(node);
				}
				List<PublicCategory> childrens = children.getChildren();
				if (childrens != null && childrens.size() > 0) {
					build(childrens, node);
				}
			}
		}
		return tree;
	}

	public PublicCategory add(PublicCategoryAdd category) throws CategoryNotFindException {
		PublicCategory publicCategory = new PublicCategory();
		if (category == null) {
			throw new CategoryNotFindException();
		}
		BeanUtils.copyProperties(category, publicCategory);
		publicCategory.setLeaf(category.isLeaf());
		return publicCategoryRepo.saveAndFlush(publicCategory);
	}

	public PublicCategory update(Long categoryId, PublicCategoryModify category) throws Exception {

		PublicCategory publicCategory = new PublicCategory();
		if (category == null) {
			throw new CategoryNotFindException();
		}
		BeanUtils.copyProperties(category, publicCategory);

		/* 如果存在parent对象，则说明正在执行变更父节点操作 */
		if (publicCategory.getParent() != null) {

			/* 检查当前节点是否存在子节点 */
			PublicCategory entity = publicCategoryRepo.findOne(categoryId);
//			if (entity.getChildren() != null && entity.getChildren().size() > 0) {
//				throw new NodeRelationException(); // 节点关联异常
//			}

			if (publicCategory.isLeaf() != entity.isLeaf()) {
				throw new ChangeIsLeafException(); // 改变节点类型异常
			}
		}

		publicCategory.setId(categoryId);
		return publicCategoryRepo.saveAndFlush(publicCategory);
	}

	public void delete(Long categoryId) throws NodeRelationException, DataRelationException {

		/* 检查当前节点是否存在子节点 */
		PublicCategory entity = publicCategoryRepo.findOne(categoryId);
		if (entity.getChildren() != null && entity.getChildren().size() > 0) {
			throw new NodeRelationException(); // 节点关联异常
		}

		/* 检查当前节点是否存在商品数据 */
		int count = publicCommodityRepo.countByCategoryId(categoryId);
		if (count > 0) {
			throw new DataRelationException(); // 数据关联异常
		}

		publicCategoryRepo.delete(categoryId);
	}

//	private boolean check(int optType, Long categoryId) {
//		PublicCategory entity = publicCategoryRepo.findOne(categoryId);
//		if (entity.getChildren() != null && entity.getChildren().size() > 0) {
//
//		}
//		return false;
//	}

	public Long[] getIds(Long categoryId) {
		List<CategoryTree>tree = getTree( categoryId);	//目录树结构对象列表
		//取出所有子节点
		for (int i=0;i< tree.size();i++) {
			if (tree.get(i).getChildren() != null) {	
				tree.addAll(tree.get(i).getChildren());
			}
		}
		List<Long> categoryIds = tree.stream()
				//.filter(item -> item.isLeaf() == false)
				.collect(
						() -> new ArrayList<Long>(),
						(list, item) -> list.add(Long.valueOf(item.getValue())),
						(list1, list2) -> list1.addAll(list2)
						);
		return categoryIds.toArray(new Long[categoryIds.size()]);
	}

	public PublicCategory findOne(Long categoryId) {
		return publicCategoryRepo.findOne(categoryId);
	}
}